package com.fvision.camera.presenter;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.SoundPool;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.fvision.camera.BuildConfig;
import com.fvision.camera.R;
import com.fvision.camera.appupgrade.UpgradeManager;
import com.fvision.camera.bean.CameraStateBean;
import com.fvision.camera.http.HttpRequest;
import com.fvision.camera.iface.ICameraStateChange;
import com.fvision.camera.manager.CameraStateIml;
import com.fvision.camera.manager.CmdManager;
import com.fvision.camera.manager.PermissionsChecker;
import com.fvision.camera.manager.SanctionManager;
import com.fvision.camera.receiver.UsbStatesReceiver;
import com.fvision.camera.service.ForegroundService;
import com.fvision.camera.utils.CameraStateUtil;
import com.fvision.camera.utils.LogUtils;
import com.fvision.camera.utils.SharedPreferencesUtil;
import com.fvision.camera.view.activity.PermissionsActivity;
import com.fvision.camera.view.customview.DialogAbout;
import com.fvision.camera.view.customview.DialogSetting;
import com.fvision.camera.view.customview.InstallPackagesPermissionDialog;
import com.serenegiant.usb.IFrameCallback;
import com.huiying.cameramjpeg.SearchUSB;
import com.huiying.cameramjpeg.UvcCamera;

import com.fvision.camera.MainActivity;
import com.fvision.camera.base.BasePresenter;
import com.fvision.camera.view.iface.IMainView;

import java.util.HashMap;

import v4.app.ActivityCompat;

/**
 * Presenter
 *
 * @author
 */

public class MainPresenter extends BasePresenter<IMainView, MainActivity> {
    private IMainView iView = null;
    private SoundPool mSoundPool;
    private int camara_sound_id = -1;
    private MainActivity mActivity;
    private UsbStatesReceiver receiver = null;
    private boolean onlyOnce = false;//只执行一次
    private SearchUSB searchUSB;
    private InstallPackagesPermissionDialog mInstallPackagesPermissionDialog;
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    private PermissionsChecker mPermissionsChecker; // 权限检测器

    public MainPresenter(IMainView view, MainActivity activity) {
        super(view, activity);
        LogUtils.d("MainPersenter 构造");
        mActivity = activity;
        iView = view;
        receiver = new UsbStatesReceiver(activity, iView, this);
    }


    public void startCamera(final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!UvcCamera.getInstance().isInit()) {
                    UvcCamera.getInstance().setPkgName(BuildConfig.APPLICATION_ID);
                    if (path == null) {
                        UvcCamera.getInstance().initUvccamera();
                    } else {
                        UvcCamera.getInstance().initUvccameraByPath(path);
                    }
                }
                if (UvcCamera.getInstance().isInit()) {
                    if (!UvcCamera.getInstance().isPreviewing()) {
                        UvcCamera.getInstance().startPreview();
                        LogUtils.d("startPreview()");
                    }
                    CmdManager.getInstance().syncTime();// 测试才注释掉
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();
    }

    public void playVoice() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mActivity);
        boolean is_snapshot_voice = sp.getBoolean(DialogSetting.KEY_SNAPSHOTVOICE, true);
        if (!is_snapshot_voice) {
            return;
        }
        initVoice();
        mSoundPool.play(1, 1, 1, 0, 0, 1);
    }

    public void playAdasSound(){
        initVoice();
        mSoundPool.play(2, 1, 1, 0, 0, 1);
    }

    private void initVoice() {
        if (mSoundPool == null) {
            mSoundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
            mSoundPool.load(mActivity, R.raw.camera_click, 1);
            mSoundPool.load(mActivity,R.raw.adas_ldw,2);
        }
    }


    /**
     * 插U盘
     */
    public void insertUsb(final String path) {
        startCamera(path);
    }

    /**
     * 拔U盘
     */
    public void pullUsb() {
//        UvcCamera.getInstance().stopPreview();
//        UvcCamera.getInstance().releaseUvccamera();
//        mActivity.stopService(new Intent(mActivity, ForegroundService.class));
//        mActivity.finish();
//        mActivity.stopService(new Intent(mActivity, ForegroundService.class));
//        ActivityStackManager.getManager().exitApp(mActivity);
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    private DialogAbout mDialogAbout = null;

//    public boolean checkPremission() {
//        return mPermissionsChecker.lacksPermissions(PERMISSIONS);
//    }

    /**
     * 显示版本
     */
    public void showAppVersion() {
        if (mDialogAbout == null) {
            mDialogAbout = new DialogAbout(mActivity);
            mDialogAbout.setUpdateClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Build.VERSION.SDK_INT >= 26) {
                        boolean b = mActivity.getPackageManager().canRequestPackageInstalls();
                        if (b) {
                            installApp();//安装应用的逻辑(写自己的就可以)
                        } else {
                            if(mInstallPackagesPermissionDialog == null){
                                mInstallPackagesPermissionDialog = new InstallPackagesPermissionDialog(mActivity);
                            }
                            mInstallPackagesPermissionDialog.show();
                            mInstallPackagesPermissionDialog.setOnFloatWindonsClickLinteners(new InstallPackagesPermissionDialog.OnFloatWindonsClickLinteners() {
                                @Override
                                public void onOk(View view) {
                                    startAppSettings();
                                }

                                @Override
                                public void onCancel(View view) {

                                }
                            });
//                            PermissionsActivity.startActivityForResult(mActivity, 222, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES});
                            //请求安装未知应用来源的权限  
//                            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 222);
                        }
                    } else {
                        installApp();
                    }
                }
            });
        }
        String deviceVersion = CmdManager.getInstance().getCurrentState().getPasswd();
        LogUtils.d("1 deviceVersion " + deviceVersion);
        mDialogAbout.setAppVersion(mActivity.getString(R.string.app_version_format, getAppVersionName(mActivity)));
        mDialogAbout.setDeviceVersion(mActivity.getString(R.string.device_version_format, deviceVersion));
        mDialogAbout.show();
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + mActivity.getPackageName()));
        mActivity.startActivity(intent);
    }

    private void installApp(){
        if (!CameraStateUtil.isNetworkAvalible(mActivity)) {
            getView().showToast(getActivity().getString(R.string.no_network));
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {

                getView().showLoading();

                UpgradeManager.getInstance().checkUpdate();
            }
        }).start();
    }

    private DialogSetting mDialogSetting;

    public void showSettingDialog() {
        if (mDialogSetting == null) {
            mDialogSetting = new DialogSetting(mActivity);
            mDialogSetting.setFormatClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    showFormatSdDialog();
                    showAppVersion();
                    mDialogSetting.dismiss();
                }
            });
        }
        mDialogSetting.show();
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    public String checkResult() {
        StringBuffer result = new StringBuffer();
        String ver = SharedPreferencesUtil.getLastDevVersion(mActivity);
        String path = UvcCamera.getInstance().getDevpath();
        if (TextUtils.isEmpty(path)) {
            result.append(mActivity.getString(R.string.undetected_device) + "\n");
        } else {
            result.append("记录仪路径:" + path + "\n");
        }
//            result.append("固件版本:"+CmdManager.getInstance().getCurrentState().getPasswd()+"\n");
        result.append(getActivity().getString(R.string.last_info_cord) + "\n");
        result.append(getActivity().getString(R.string.device_version) + ver + "\n");
        result.append(getActivity().getString(R.string.app_version) + CameraStateUtil.getVersionName(mActivity) + "\n");
        result.append(getActivity().getString(R.string.android_version) + Build.VERSION.SDK_INT + "(" + Build.VERSION.RELEASE + ")" + "\n");
        result.append(getActivity().getString(R.string.device_model) + Build.MODEL + "\n");
        result.append("fd error:" + UvcCamera.getInstance().fd_error + "\n");
        result.append("cmd fd error:" + UvcCamera.getInstance().cmd_fd_error + "\n");

        return result.toString();
    }

    public void checkPermission(int request_code) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        // 缺少权限时, 进入权限配置页面
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
            //mView.showToast(mActivity.getString(R.string.no_permission));
            startPermissionsActivity(request_code);//v4注释
        }
    }

    public void startPermissionsActivity(int request_code) {
        PermissionsActivity.startActivityForResult(mActivity, request_code, PERMISSIONS);
    }

    private void initHttp() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        UpgradeManager.init(mActivity, "DriverRecord.apk");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        initUsbReciver();
        LogUtils.d("MainPersenter onCreate");
        initHttp();
//        initVoice();
        mPermissionsChecker = new PermissionsChecker(mActivity);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();


//        if (UvcCamera.getInstance().isInit() && UvcCamera.getInstance().isPreviewing()) {
//            UvcCamera.getInstance().stopPreview();
//        }
//        UvcCamera.getInstance().releaseUvccamera();


//        mActivity.unregisterReceiver(broadcast);
        if (mSoundPool != null) {
            mSoundPool.release();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.d("MainPersenter onResume");
        CameraStateIml.getInstance().setOnCameraStateListner(new ICameraStateChange() {
            @Override
            public void stateChange() {
                iView.resrefhView();
            }
        });
        UvcCamera.getInstance().setStateFrameCallback(CameraStateIml.getInstance().mStateFrameCallback);

        if (CmdManager.getInstance().getCurrentState() != null
                && !CmdManager.getInstance().getCurrentState().isCam_rec_state()) {
            CmdManager.getInstance().recToggle();
        }
    }

    public void showFormatSdDialog() {
        CameraStateBean state = CmdManager.getInstance().getCurrentState();
        if (onlyOnce || !state.isCam_sd_state() || !state.isCam_tf_cu_state()) {//已经弹过一次 || 无SD卡 || 不需要格式化
            return;
        }
        onlyOnce = true;
        new AlertDialog.Builder(mActivity).setTitle(R.string.notifycation).setMessage(R.string.confirm_format_tfcard)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        CmdManager.getInstance().formatTf();
                    }
                }).setNegativeButton(R.string.no, null).create().show();
    }

    public void getSanction(){
        if(!CameraStateUtil.isNetworkAvalible(mActivity)){
            return;
        }
        String androidVer = Build.VERSION.SDK_INT + "(" + Build.VERSION.RELEASE + ")" ;
        String appVer = CameraStateUtil.getVersionName(mActivity);
        String devVer = SharedPreferencesUtil.getLastDevVersion(mActivity);
        String devModel = Build.MODEL;
        String recorder_id = CmdManager.getInstance().getDVRUid();
        String recorder_model = "建荣 - 小";
       // String imei = CameraStateUtil.getImei(mActivity);

        int vendor;
        if(CmdManager.getInstance().isSupportSanction()){
            vendor = CmdManager.getInstance().getVendor();
        }else {
            vendor = 616;
        }
        HashMap<String ,String> params = new HashMap<>();
        params.put("recorder_id",recorder_id);
        params.put("recorder_model",recorder_model);
        params.put("recorder_version",devVer);
        params.put("app_version",appVer);
        params.put("car_pad_model",devModel);
        params.put("android_version",androidVer);
        params.put("imei","");
        params.put("gps_address","");
        params.put("local_vendor_id",""+vendor);
        params.put("local_vendor_name", SanctionManager.getSanctionName(vendor));
        params.put("expand1","");
        params.put("expand2","");
        params.put("expand3","");
//{local_vendor_id=1, recorder_id=38333819004f8384, app_version=1210_v1.3.1, expand3=, imei=866417040007899, android_version=22(5.1.1), gps_address=, car_pad_model=Full AOSP on Sofia, expand1=, local_vendor_name=测试公司, recorder_version=1221_v2.DBG.He, expand2=, recorder_model=升迈}
        LogUtils.d(params.toString());

        HttpRequest.requestSanction(params, new HttpRequest.SanctionIFace() {
            @Override
            public void onSuccess(boolean isSanction) {
                SharedPreferencesUtil.setSanction(mActivity,isSanction);
//                mView.showToast(isSanction?"需要制裁":"");
                mView.resrefhView();
            }

            @Override
            public void onFail(int errorCode, String error) {

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        receiver.registerReceiver();
    }

    @Override
    public void onStop() {
        super.onStop();
        receiver.unregisterReceiver();
    }


}
